<?php

namespace app\common\model\banxi\organization;

use app\common\enums\core\AuditStateEnum;
use app\common\enums\core\UserTypeEnum;
use app\common\enums\OrganizationStateEnum;
use app\common\enums\QuotaBusinessTypeEnum;
use app\common\model\banxi\sys\SysUser;
use app\common\model\common\BaseModel;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\model\concern\SoftDelete;

/**
 * 机构等级配置
 */
class OrganizationOpenApply extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_organization_open_apply';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'applyStateCn',
        'applyUserTypeCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'applyUserId' => 'string',
        'applyOrganizationUserId' => 'string',
        'auditUserId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];

    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getApplyStateCnAttr($value, $data)
    {
        $value = $value ?: ($data['applyState'] ?? '');
        return (new AuditStateEnum())->getDescription($value) ?? '';


    }

    public function getApplyUserTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['applyUserType'] ?? '');
        return (new UserTypeEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    public function getListPage(array $where, int $page = 1, int $limit = 10)
    {
        return $this->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,managerName,name');
            }, 'applyOrganizationUserInfo',
            'applyUserInfo'
        ])->where($where)
            ->order(['id' => 'desc', 'applyState' => 'desc'])
            ->paginate([
                'page' => $page,
                'list_rows' => $limit
            ])->each(function ($item) {
                if ($item['applyOrganizationId'] == 0) {
                    $organization = new Organization();
                    $item['organizationBaseInfo'] = $organization->getOrganizationInfo();
                }
                $item['applyUserName'] = '超级管理员';
                if ($item['applyUserInfo']) {
                    $item['applyUserName'] = $item['applyUserInfo']['nickName'];
                }
                if ($item['applyOrganizationUserInfo']) {
                    $item['applyUserName'] = $item['applyOrganizationUserInfo']['realName'];
                }
            });
    }

    public function getInfo(array $where)
    {
        $list = $this->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,managerName,name');
            }
        ])->where($where)->find();
        if (!$list) {
            return [];
        }
        if ($list['applyOrganizationId'] == 0) {
            $organization = new Organization();
            $list['organizationBaseInfo'] = $organization->getOrganizationInfo();
        }
        return $list;
    }

    public function del(string|int $openApplyId, string $organizationId = "0")
    {
        $this->startTrans();
        try {
            $openApply = $this->where(['id' => $openApplyId])->find();
            if (!$openApply) {
                throw new ValidateException('申请记录不存在');
            }
            $applyUserType = $openApply['applyUserType'];
            if ($applyUserType == 'organization' && $openApply['applyOrganizationId'] != $organizationId) {
                throw new ValidateException('无权限操作该数据');
            }
            $applyState = $openApply['applyState'];
            if ($applyState == AuditStateEnum::E1 && $applyUserType == 'organization') {
                $organizationQuotaRw = new OrganizationQuotaRw();
                $trade = [
                    "describe" => "开户申请删除 【{$openApply['organizationName']}】",
                    'organizationId' => $organizationId,
                    'value' => 1,
                    'businessType' => QuotaBusinessTypeEnum::E3,
                    'businessId' => $openApply['id']
                ];
                $organizationQuotaRw->updateAccount($trade);
            }
            if($applyState != AuditStateEnum::E2){
                $delOrganizationId = $openApply['organizationId'];
                Organization::destroy([
                    'id' => $delOrganizationId,
                    'status' => OrganizationStateEnum::E1
                ]);
                OrganizationUser::destroy(['organizationId'=>$delOrganizationId]);
            }
            $openApply->delete();
            $this->commit();
        } catch (PDOException|Exception|ValidateException $e) {
            $this->rollback();
            throw new ValidateException($e->getMessage());
        }
        return true;


    }

    public function updateAuditById($openApplyId, $auditUserId, $auditUserName, $result)
    {
        return $this->update([
            'auditUserId' => $auditUserId,
            'auditUserName' => $auditUserName,
            'applyState' => $result ? 2 : 3
        ], ['id' => $openApplyId, 'applyState' => 1]);
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function organizationBaseInfo()
    {
        return $this->hasOne(Organization::class, 'id', 'applyOrganizationId');
    }

    public function applyOrganizationUserInfo()
    {
        return $this->hasOne(OrganizationUser::class, 'organizationId', 'applyOrganizationId');
    }

    public function applyUserInfo()
    {
        return $this->hasOne(SysUser::class, 'id', 'applyUserId');
    }

}